new FastClick(document.body);
//封装cordova的执行方法，加上回调函数
var cordovaExec = function (plugin, action, parameters, callback) {
    cordova.exec(function (data) {
            if (callback !== undefined) {
                callback();
            }
        }
        , function (err) {}
        , plugin
        , action
        , parameters === null || parameters === undefined ? [] : parameters);
};
var backToMain = function () {
    $(".back_btn").trigger("click");
};

//首页接受到信息，刷新页面
var receiveMessage = function (identifier, count, display) {
    var $moduleTips = $(".module_Tips[moduletype='main'][identifier='" + identifier + "']");
    if (display && count > 0) {
        $moduleTips.html(count);
        $moduleTips.show();
    } else {
        $moduleTips.hide();
    }
    if (myScroll) {
        myScroll.refresh();
    }
};

//自动更新查新界面
var refreshMainPage = function (identifier, type, moduleMessage) {
    console.log("refreshMainPage" + type + "..." + identifier);
    if (localStorage.bslsessionKey) {
        //console.log("有bslsessionKey");
        $('#login_btn').html("登出");
    } else {
        //console.log("无bslsessionKey");
        $('#login_btn').html("登录");
    }
    if (($('.homeclick').hasClass('active')) && isOver === 0) {
        //主页面
        //console.log("进入main页面");
        isOver = isOver + 1;
        loadModuleList("CubeModuleList", "mainList", "main", function () {
            if (myScroll) {
                myScroll.refresh();
            }
            isOver = isOver - 1;
        });
    }
};
var refreshManagerPage = function () {
    //console.log("refreshManagerPage ");
    if (($('.managerclick').hasClass('active')) && isOver === 0) {
        //主页面
        //console.log("进入manager页面");
        isOver = isOver + 1;
        //console.log("刷新。。。。");
        var type = $(".buttom_btn_group .btn.active").attr("data");
        var t = type;
        if (type == "upgrade") {
            type = "upgradable";
        }
        loadModuleList("CubeModuleList", type + "List", t, function () {
            //listLayout();
            if (myScroll) {
                myScroll.refresh();
            }
            isOver = isOver - 1;
        });
    }
}

var loginOrLogout = function (isLogin) {
    if (!isLogin) {
        if (localStorage.bslsessionKey) {
            localStorage.removeItem("bslsessionKey");
        }
        cordova.exec(function (plugindata) {
        }, function () {
        }, "CubeLogoutPlugin", "logout", []);
    } else {
        cordovaExec("CubeModuleOperator", "showModule", ["com.foss.phonelogin", "main"]);
    }
};


$("#login_btn").bind("click", function () {
    //console.log("localStorage.bslsessionKey = " + localStorage.bslsessionKey);
    if (localStorage.bslsessionKey) {
        //alert("现在登出");
        var notifacation_onConfirm = function (buttonIndex) {
            if (buttonIndex == 1) {
                //alert("1");
                localStorage.removeItem("bslsessionKey");
                cordova.exec(function (plugindata) {
                    //console.log("bslse调用CubeLogoutPlugin");
                    //$('#login_btn').html("登录");
                    ////console.log(plugindata);
                }, function () {

                }, "CubeLogoutPlugin", "logout", []);
            }
        };
        navigator.notification.confirm(
            '是否要登出？', // message
            notifacation_onConfirm, // callback to invoke with index of button pressed
            '提示', // title
            ['确定', '取消'] // buttonLabels
        );
    } else {
        //alert("现在登录");
        //localStorage.bslsessionKey = "adfsdfasdfasfsdf";
        cordovaExec("CubeModuleOperator", "showModule", ["com.foss.phonelogin", "main"]);
    }
});

$(".homeclick").bind("click", function () {
    if (!$(this).hasClass("active")) {
        $(".tab-item").removeClass("active");
        $(this).addClass("active");
        $(".managerclick").html('<img src="img/manager_gray.png" style="width:24px; height:24px;">').append('<div style="font-size:13px;color:#666666;">管理</div>');
        $(".homeclick").html('<img src="img/home_orange.png" style="width:24px; height:24px;">').append('<div style="font-size:13px;color:#8d8d8d;">主页</div>');

        //$('#top_left_btn').removeClass('back_bt_class');
        //gridLayout();
        $('.buttomContent').css('display', 'none');
        $("#wrapper").css("top", "44px");

        $('#title').html("变色龙");
        $('#login_btn').show();

        loadModuleList("CubeModuleList", "mainList", "main", function () {
            gridLayout();
            if (myScroll) {
                myScroll.refresh();
                //$('#top_left_btn').removeClass("disabled");
            }

        });
    }

});
$(".managerclick").bind("click", function () {
    $(".tab-item").removeClass("active");
    $(this).addClass("active");
    $(".homeclick").html('<img src="img/home_gray.png" style="width:24px; height:24px;">').append('<div style="font-size:13px;color:#666666;">主页</div>');
    $(".managerclick").html('<img src="img/manager_orange.png" style="width:24px; height:24px;">').append('<div style="font-size:13px;color:#8d8d8d;">管理</div>');
    cordovaExec("CubeModuleOperator", "sync", [], function () {
        //alert("管理同步成功");

        //完成后设置listview
        $('.buttomContent').css('display', 'block');
        $("#wrapper").css("top", "94px");
        $('#title').html("模块管理");
        $('#login_btn').hide();
        //console.log("listLayout");
        loadModuleList("CubeModuleList", "uninstallList", "uninstall", function () {
            listLayout();
            //console.log("loadModuleList 数据完成");
            //$('.module_div ul li .curd_btn').css('display', 'inline');
            isOver = 0;
            var type = "uninstall";
            //console.log("44");
            activeModuleManageBarItem(type);

            //cordovaExec("CubeModuleOperator", "manager");
            //console.log("5");
            if (myScroll) {
                myScroll.refresh();
            }
            //console.log("6");

        });
        //console.log("同步成功");
        //myScroll.refresh();
    });


});
$(".settingclick").bind("click", function () {
    //cordovaExec("CubeModuleOperator", "setting");
    cordovaExec("CubeModuleOperator", "showModule", ["com.foss.setting", "main"]);
});

//进度获取
var updateProgress = function (identifier, count) {
    ////console.log(identifier + '进入updateProgress');
    if (count == -1) {
        $(".module_div ul li .module_li_img .progress[identifier='" + identifier + "']").css('display', 'block');
    } else if (count >= 0 && count <= 100) {
        //console.log("count>=0 && count <=100 " + count);
        $(".module_div ul li .module_li_img .progress[identifier='" + identifier + "']").css('display', 'block');
        $(".module_div ul li .module_li_img .progress[identifier='" + identifier + "'] .bar").css('width', count + "%");
    } else if (count == 101) {
        $(".module_div ul li .module_li_img .progress[identifier='" + identifier + "']").css('display', 'none');
    }
};

//模块增删，刷新模块列表(uninstall，install，upgrade)
var refreshModule = function (identifier, type, moduleMessage) {
    if ($('.managerclick').hasClass('active')) {
        //console.log("进入refreshModule " + type + "..." + identifier);

        if (type === "uninstall") {
            //console.log("进入uninstall");
            //已安装减一个
            //console.log("已安装页面减一个");
            $(".module_li[moduletype='install'][identifier='" + identifier + "']").remove();
            if ($("#uninstallBtn").hasClass("active")) {
                //未安装加一个
                addModule(identifier, "uninstall", moduleMessage);
                //console.log("未安装的加一个成功");
            }

            //更新有则减

            $(".module_li[moduletype='upgrade'][identifier='" + identifier + "']").remove();
        } else if (type === "install") {
            //console.log("进入install");
            //未安装减一个
            $(".module_li[moduletype='uninstall'][identifier='" + identifier + "']").remove();
            $(".module_li[moduletype='upgrade'][identifier='" + identifier + "']").remove();
            if ($("#installBtn").hasClass("active")) {
                //已安装加一个
                addModule(identifier, "install", moduleMessage);
            }
            //更新不变
        } else if (type === "upgrade") {
            //更新减一个
            $(".module_li[moduletype='upgrade'][identifier='" + identifier + "']").remove();
            //已安装替换
            //addModule(identifier, "install", moduleMessage);
            //未安装不变
        } else if (type === "main") {
            //addModule(identifier, "main", moduleMessage);
        }
    } else {
        //主页面
        ////console.log("主界面、、");
        //$("li[identifier='" + identifier + "']").css('opacity', '1');
        //判断模块 hidden
        var isHidden = $("li[identifier='" + identifier + "']").attr("hidden");
        ////console.log("是否显示？？？？" + isHidden);
        if (isHidden == "true") {
            $("li[identifier='" + identifier + "']").remove();
        }
    }
    checkModules();
    if (myScroll) {
        myScroll.refresh();
    }


};
var addModule = function (identifier, type, moduleMessage) {
    var mm = moduleMessage;
    if (!(moduleMessage instanceof Object)) {
        mm = $.parseJSON(moduleMessage);
    }

    var isuninstallpage = false;
    if ($(".managerclick").hasClass("active") && $("#uninstallBtn").hasClass("active")) {
        isuninstallpage = true;
    }
    //如果该模块不存在，则生成
    if ($(".scrollContent_li[modules_title='" + mm.category + "']").size() < 1) {
        var tag = $(".scrollContent_li").size();
        //获取模板名
        var moduleContentTemplate = $("#t2").html();
        var moduleContentHtml = _.template(moduleContentTemplate, {
            'muduleTitle': mm.category,
            "tag": tag
        });
        $(".mainContent").find(".scrollContent").append(moduleContentHtml);
    }

    //如果存在，先删除，再添加
    if ($("li[identifier='" + identifier + "']").size() > 0) {
        $("li[identifier='" + identifier + "']").remove();
    }

    var moduleItemTemplate = $("#module_div_ul").html();

    //更新的图标，如果在未安装里面，不应该出现
    if (type === 'uninstall') {
        mm.updatable = false;
    }

    mm.name = subStrByCnLen(mm.name + "", 9);

    if ($('.homeclick').hasClass('active')) {
        mm.name = subStrByCnLen(mm.name + "", 5);
    }
    var privileges = "null";
    if (mm.privileges) {
        //console.log("privileges存在");
        privileges = mm.privileges;
    } else {
        //console.log("privileges不存在");
    }

    mm.releaseNote = subStrByCnLen(mm.releaseNote + "", 13);

    //console.log("privileges -----" + privileges);
    var moduleItemHtml = _.template(moduleItemTemplate, {
        'icon': mm.icon,
        'name': mm.name,
        'moduleType': type,
        'identifier': mm.identifier,
        'version': mm.version,
        'releasenote': mm.releaseNote,
        'btn_title': changeBtnTitle(type),
        "updatable": mm.updatable,
        "local": mm.local,
        "msgCount": mm.msgCount,
        "hidden": mm.hidden,
        "privileges": privileges,
        "isuninstallpage": isuninstallpage
    });
    $(".scrollContent_li[modules_title='" + mm.category + "']").children('div').children('ul').append(moduleItemHtml);


    if (myScroll) {
        myScroll.refresh();
    }


};
//检查模块信息的完整性，如果没有模块，则隐藏
var checkModules = function () {
    //console.log('AAAAAA----检查模块信息的完整性，如果没有模块，则隐藏');
    $.each($(".scrollContent_li"), function (index, data) {

        if ($(this).children('.module_div').children('.module_div_ul').children('.module_li').size() < 1) {
            $(this).remove();

        } else {
            var show_module_lis = $(this).children('.module_div').children('.module_div_ul').children('.module_li');
            $.each($(show_module_lis), function (i, show_module_li) {
                if ($(show_module_li).css('display') == "none") {
                    //console.log("有隐藏的对象");
                    $(show_module_li).parent('.module_div_ul').parent('.module_div').parent('.scrollContent_li').remove();
                }
            });
        }
    });
};

var changeBtnTitle = function (type) {
    //alert("进入changeBtnTitle");
    switch (type) {
        case "install":
            return "删除";
            break;
        case "uninstall":
            return "安装";
            break;
        case "upgradable":
            return "更新";
            break;
        case "upgrade":
            return "更新";
            break;
        case "main":
            return "删除";
            break;

    }
    //alert("完成changeBtnTitle");
};
/*$(document).ready(function() {*/
// 选中模块操作菜单，传入需要激活的按钮名称（uninstall，install，upgrade）
var activeModuleManageBarItem = function (type) {
    // 移除所有选中
    $(".buttomContent .buttom_btn_group .btn").removeClass("active");
    // 选中当前点击
    $(".buttomContent .buttom_btn_group .btn[data='" + type + "']").addClass("active");
};

//点击模块的时候触发事件
var module_all_click = function () {
    $("li[identifier]").live('click', function () {
        var type = $(this).attr("moduleType");
        var identifier = $(this).attr("identifier");
        console.log('触发点击事件 id=' + identifier);
        cordovaExec("CubeModuleOperator", "showModule", [identifier, type]);
    });
};


var changeLayout = function (oldfilename, newfilename, type) {
    //replacejscssfile("css/gridview.css", "css/listview.css", "css");
    replacejscssfile(oldfilename, newfilename, type);
}


// 加载列表，渲染成html
var isOver = 0;
var loadModuleList = function (plugin, action, type, callback) {
    console.log('BBBBBB------loadModuleList');
    cordova.exec(function (data) {
            console.log("BBBBBB----loadMuduleList回调");
            console.log(data.toString());
            data = $.parseJSON(data);
            var i = 0;
            $('.temul').html("");
            var isuninstallpage = false;
            if ($(".managerclick").hasClass("active") && $("#uninstallBtn").hasClass("active")) {
                isuninstallpage = true;
            }
            _.each(data, function (value, key) {
                console.log("外循环A key=" + key + ",value= " + value.toString());
                $('.temul').append(_.template($("#t2").html(),
                    {
                        'muduleTitle': key,
                        'tag': i
                    }
                ));
                _.each((value), function (value, key) {
                    //更新的图标，如果在未安装里面，不应该出现
                    console.log("内循环A key=" + key + ",value= " + value.toString());
                    for (var kk in value) {
                        console.log(kk + " = " + value[kk]);
                    }
                    if (type === 'uninstall') {
                        value.updatable = false;
                    }
                    value.name = subStrByCnLen(value.name + "", 9);
                    if ($('.homeclick').hasClass('active')) {
                        value.name = subStrByCnLen(value.name + "", 5);
                    }
                    var privileges = "null";
                    if (value.privileges) {
                        privileges = value.privileges;
                    }

                    value.releaseNote = subStrByCnLen(value.releaseNote + "", 13);
                    $('.module_div_ul[num="' + i + '"]').append(
                        _.template($("#module_div_ul").html(), {
                            'icon': value.icon,
                            'name': value.name,
                            'moduleType': type,
                            'identifier': value.identifier,
                            //'version': value.version,
                            'releasenote': value.releaseNote,
                            'btn_title': changeBtnTitle(type),
                            "updatable": value.updatable,
                            "local": value.local,
                            "msgCount": value.msgCount,
                            "hidden": value.hidden,
                            "privileges": privileges,
                            "isuninstallpage": isuninstallpage
                        }));
                });

                i = i + 1;
            });

            $(".myul").html($(".temul").html());
            $(".temul").html("");
            $(".mainContent").css('padding-bottom', '20px');
            i = 0;
            //console.log("完成initial方法");
            checkModules();
            $("li[identifier]").die("click");
            module_all_click();
            if (myScroll) {
                myScroll.refresh();
            }
            //如果回调方法不为空，则执行该回调方法
            if (callback !== undefined) {
                callback();
            }
            //console.log("完成loadMuduleList");
        },
        function (err) {
            isOver = isOver - 1;
        }, plugin, action, []);

};
var listLayout = function () {
    //console.log("listview");
    changeLayout("css/gridview.css", "css/listview.css", "css");
    setTimeout(function () {
        if (myScroll) {
            myScroll.refresh();
            myScroll.scrollTo(0, 0, 200, false);
        }
    }, 100);
};

var gridLayout = function () {
    //console.log("gridview");
    changeLayout("css/listview.css", "css/gridview.css", "css");
    $("li[identifier]").css("background", "#ffffff");
    //设置titlename位置
    $('.detail .module_li_titlename').css('font-size', '0.9em').css("top", "10px");
    setTimeout(function () {
        if (myScroll) {
            myScroll.refresh();
            //myScroll.scrollTo(0, 0, 200, false);
        }
    }, 100);
}

//处理底下按钮
$(".buttomContent .buttom_btn_group .btn").click(function () {
    var type = $(this).attr("data");
    //console.log("butom type=" + type);
    if (!$(this).hasClass("active")) {
        activeModuleManageBarItem(type);
        var t = type;
        if (type == "upgrade") {
            type = "upgradable";
        }

        loadModuleList("CubeModuleList", type + "List", t, function () {
            //listLayout();
            if (myScroll) {
                myScroll.refresh();
            }
        });
    }
});

//---------------------------------------------------------------------------------------------
var myScroll = null;
//应用初始化
var app = {
    initialize: function () {
        this.bindEvents();
    },
    bindEvents: function () {
        document.addEventListener('deviceready', this.onDeviceReady, false);
        /*var browser = navigator.appName;
         if (browser !== "Microsoft Internet Explorer") {
         new FastClick(document.body);
         }*/
    },
    onDeviceReady: function () {
        app.receivedEvent('deviceready');
    },
    receivedEvent: function (id) {
        //console.log("receivedEvent");
        myScroll = new iScroll("wrapper", { hScrollbar: false, vScrollbar: false, checkDOMChanges: true, zoom: false, useTransform: false});
        if (localStorage.bslsessionKey) {
            localStorage.removeItem("bslsessionKey");
        }
        loadModuleList("CubeModuleList", "mainList", "main", function () {
            cordovaExec("CubeModuleOperator", "sync", [], function () {
                //console.log("同步成功");
                loadModuleList("CubeModuleList", "mainList", "main", function () {
                    if (myScroll) {
                        myScroll.refresh();
                    }
                });
            });
        });
    }
};
app.initialize();